<?php

namespace app\system\controller;

use app\common\model\AttachmentModel;
use OSS\OssClient;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use think\Db;
use think\Request;

class AttachmentController extends BaseController
{

    private $attachmentModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->attachmentModel = new AttachmentModel();
    }

    /**
     * 附件管理
     * @return mixed
     */
    public function index()
    {
        $map = [];
        $query = $this->request->request();
        $groupId = $this->request->param('group_id/d', 0);
        $map['group_id'] = $groupId;
        $map['uid'] = $this->getUid(); //只能管理自己上传附件
        $searchKey = $this->request->param('searchKey');
        $searchText = $this->request->param('searchText');
        if (!empty($searchKey) && !empty($searchText)) {
            $map[$searchKey] = ['like', '%' . $searchText . '%'];
        }
        $list = $this->attachmentModel->where($map)->order('id desc')->paginate(10, false, [
            'query' => $query,
        ]);
        $groupList = Db::table('attachment_group')->where('uid', $this->getUid())->select();
        $this->assign('utype', $this->getUtype());
        $this->assign('groupList', $groupList);
        $this->assign('list', $list);
        $this->assign('query', $query);
        return $this->fetch();
    }

    /**
     * 删除附件
     */
    public function del()
    {
        try{
            $id = $this->request->param('id');
            if (is_numeric($id)) {
                $info = $this->attachmentModel->get($id);
                $this->attachmentModel->destroy($id);
                $this->delFile($info['url'], $info['upload_type']);
            } else {
                $list = $this->attachmentModel->where('id', 'in', $id)->select()->toArray();
                foreach ($list as $v) {
                    $this->delFile($v['url'], $v['upload_type']);
                }
                $this->attachmentModel->destroy($id);
            }
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('删除成功！');
    }

    /**
     * 删除物理文件
     */
    private function delFile($url, $uploadType)
    {
        try{
            switch ($uploadType) {
                case 'upload':
                    \org\Util\FileUtil::unlinkFile('.' . $url);
                    break;
                case 'qiniu':
                    $bucket = config('base.qiniu_bucket');
                    $accessKey = config('base.qiniu_ak');
                    $secretKey = config('base.qiniu_sk');
                    $auth = new Auth($accessKey, $secretKey);
                    $bucketMgr = new BucketManager($auth);
                    $url = str_replace(config('base.upload_prefix') . '/', '', $url);
                    $bucketMgr->delete($bucket, $url);
                    break;
                case 'alioss':
                    $accessKeyId = config('base.alioss_ak');
                    $accessKeySecret = config('base.alioss_sk');
                    $endpoint = config('base.alioss_endpoint');
                    $bucket = config('base.alioss_bucket');
                    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, true);
                    $url = str_replace(config('base.upload_prefix') . '/', '', $url);
                    $ossClient->deleteObject($bucket, $url);
                    break;
            }
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 添加分组
     */
    public function addGroup()
    {
        try{
            $groupName = trim($this->request->param('group_name'));
            if (empty($groupName)) {
                $this->error('请输入分组名！');
            }
            $data = ['uid' => $this->getUid(), 'utype' => $this->getUtype(), 'group_name' => $groupName];
            Db::table('attachment_group')->insert($data);
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('操作成功！');
    }

    /**
     * 移动分组
     */
    public function moveGroup()
    {
        try{
            $ids = $this->request->param('ids');
            $groupId = $this->request->param('group_id');
            $this->attachmentModel->where('id', 'in', $ids)->setField('group_id', $groupId);
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('移动成功！');
    }

    /**
     * 编辑分组
     */
    public function editGroup()
    {
        try{
            $groupId = $this->request->param('group_id');
            $groupName = $this->request->param('group_name');
            Db::table('attachment_group')->where('group_id', $groupId)->setField('group_name', $groupName);
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('修改成功！');
    }

    /**
     * 删除分组
     */
    public function delGroup()
    {
        try{
            $groupId = $this->request->param('group_id');
            $attachInfo = $this->attachmentModel->where('group_id', $groupId)->find();
            if ($attachInfo) {
                $this->error('该分组下存在附件，不允许删除！');
            }
            Db::table('attachment_group')->where('group_id', $groupId)->delete();
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('删除成功！', url('index'));
    }

}
